import { createRouter, createWebHistory } from 'vue-router'
import { useGlobalStore } from '@/stores/global'
import { scrollToTop } from '@/utils/scroll-util'

const routes = [
  {
    path: '/',
    name: 'layout',
    component: () => import('@/components/layout/MainLayout.vue'),
    children: [
      {
        path: '',
        name: 'home',
        component: () => import('@/views/Home.vue'),
        meta: { title: '首页' },
      },
      {
        path: '/articles',
        name: 'articles',
        component: () => import('@/views/articles/ArticleList.vue'),
        meta: { title: '文章列表' },
      },
      {
        path: '/articles/:id',
        name: 'article-detail',
        component: () => import('@/views/articles/ArticleDetail.vue'),
        meta: { title: '文章详情' },
      },
      {
        path: '/categories',
        name: 'categories',
        component: () => import('@/views/categories/CategoryList.vue'),
        meta: { title: '分类浏览' },
      },
      {
        path: '/tags',
        name: 'tags',
        component: () => import('@/views/tags/TagList.vue'),
        meta: { title: '标签列表' },
      },
      {
        path: '/tags/:id',
        name: 'tag-detail',
        component: () => import('@/views/tags/TagDetail.vue'),
        meta: { title: '标签详情' },
      },
      {
        path: '/moments',
        name: 'moments',
        component: () => import('@/views/moments/Moments.vue'),
        meta: { title: '瞬间' },
      },
      {
        path: '/timeline',
        name: 'timeline',
        component: () => import('@/views/timeline/Timeline.vue'),
        meta: { title: '历程' },
      },
      {
        path: '/about',
        name: 'about',
        component: () => import('@/views/about/About.vue'),
        meta: { title: '关于' },
      },
      {
        path: '/search',
        name: 'search',
        component: () => import('@/views/search/SearchResult.vue'),
        meta: { title: '搜索' },
      },
    ],
  },
  { path: '/:path(.*)', redirect: '/' },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior() {
    scrollToTop({ behavior: 'smooth' })
  },
})

// 全局前置守卫 - 确保用户信息在每次路由切换时都已加载
router.beforeEach(async () => {
  const globalStore = useGlobalStore()
  // 统一通过ensureUserInfo异步加载用户信息，阻塞导航直到加载完成
  try {
    await globalStore.ensureUserInfo()
  } catch (error) {
    console.warn('路由切换时用户信息加载失败:', error)
  }
})

// 动态设置页面标题
router.afterEach(async to => {
  const globalStore = useGlobalStore()
  const user = await globalStore.ensureUserInfo()
  const blogName = user?.blogName || 'Tech Blog'
  if (to.meta && to.meta.title) {
    document.title = `${to.meta.title} - ${blogName}`
  } else {
    document.title = blogName
  }
})

export default router
